﻿Option Explicit On

'TWILT - Tweet What I'm Listening To - Coded by -DefaulT
'Copyright (C) 2011  -DefaulT

'Distributed Through http://twilt.co.cc/

'This program is free software; you can redistribute it and/or
'modify it under the terms of the GNU General Public License
'as published by the Free Software Foundation; either version 2
'of the License, or (at your option) any later version.

'This program is distributed in the hope that it will be useful,
'but WITHOUT ANY WARRANTY; without even the implied warranty of
'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
'GNU General Public License for more details.

'You should have received a copy of the GNU General Public License
'along with this program; if not, write to the Free Software
'Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

' First we need to import our library files.
Imports System.IO.File
Imports TwitterVB2
Imports HundredMilesSoftware.UltraID3Lib
Imports System.Xml

Module Twilt

    ' Lets get the public declarations out of the way
    Dim vars As New Dictionary(Of String, String)
    Public tw As New TwitterAPI

    ' Change these to your applications consumer and consumer secret token.
    Dim consumer As String = "faHE6msqfr1nNhJrGyUubA"
    Dim consumersecret As String = "eWxrtHBZStQlkE0ZyKB2zSPR2r97tBOp9bN2mmiQo"

    Public oauthtocken As String
    Public oauthtockensecret As String
    Dim strURL As String
    Dim oFile As System.IO.File
    Dim oWrite As System.IO.StreamWriter

    Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

    ' --------------------------------------------------LOGIN-----------------------------------------------------

    ' Check to see if we have already authenticated the user.
    Public Sub LoginCheck()
        If frmLogin.TextBox3.Text = "" Then
            MsgBox("Please enter a valid username.")
        Else
            Try
                ' Open first reader.
                Dim objReader As New System.IO.StreamReader(Application.StartupPath & "\Settings\" & frmLogin.TextBox3.Text & "_OAuthtk.dat")
                My.Settings.m_strToken = objReader.ReadLine()
                My.Settings.Save()
                ' Clsose the reader.
                objReader.Close()
                ' Open second reader.
                Dim objReader1 As New System.IO.StreamReader(Application.StartupPath & "\Settings\" & frmLogin.TextBox3.Text & "_OAuthtkST.dat")
                My.Settings.m_strTokenSecret = objReader1.ReadLine()
                My.Settings.Save()
                ' Close second reader.
                objReader1.Close()
                ' If all is successful and we made it this far, then lets get them to the main form and skip pin.
                ' Hide me and show main form.
                frmLogin.Hide()
                frmMain.Show()
            Catch ex As Exception
                'User hasnt been authenticated - show pin form.
                frmLogin.Hide()
                frmPin.Show()
            End Try
        End If
    End Sub

    ' --------------------------------------------------PIN-----------------------------------------------------

    ' Check pin and if it is valid, save it to the .dat files.
    Public Sub CheckPin()
        ' There is nothing in the textbox D:
        If frmPin.TextBox1.Text = Nothing Then
            MsgBox("Please Enter a Pin.")
        Else
            Dim isValid As Boolean = tw.ValidatePIN(frmPin.TextBox1.Text)
            If isValid = True Then

                ' Yay its a working pin, now lets save there authentication data in .dat files for the future.
                oauthtocken = tw.OAuth_Token
                oauthtockensecret = tw.OAuth_TokenSecret

                oWrite = IO.File.CreateText(Application.StartupPath & "\Settings\" & frmLogin.TextBox3.Text & "_OAuthtk.dat")
                oWrite.WriteLine(oauthtocken)
                oWrite.Close()

                oWrite = IO.File.CreateText(Application.StartupPath & "\Settings\" & frmLogin.TextBox3.Text & "_OAuthtkST.dat")
                oWrite.WriteLine(oauthtockensecret)
                oWrite.Close()

                frmMain.Show()
                frmPin.Hide()
            End If
        End If
    End Sub

    ' Get custom URL.
    Function GetLinkURL() As String
        Return tw.GetAuthorizationLink(consumer, consumersecret)
    End Function

    ' --------------------------------------------------MAIN-----------------------------------------------------

    ' Loading form.
    Public Sub LoadMain()

        ' Start timer1 for music information checks.
        frmMain.Timer1.Start()

        ' Start timer2 for auto refresh.
        frmMain.Timer2.Start()

        ' Start notify icon for system tray.
        frmMain.NotifyIcon1.ContextMenuStrip = frmMain.ContextMenuStrip1

        frmMain.TextBox1.BringToFront()

        'Check authentication.
        Dim objReader As New System.IO.StreamReader(Application.StartupPath & "\Settings\" & frmLogin.TextBox3.Text & "_OAuthtk.dat")
        My.Settings.m_strToken = objReader.ReadLine()
        My.Settings.Save()
        objReader.Close()

        Dim objReader1 As New System.IO.StreamReader(Application.StartupPath & "\Settings\" & frmLogin.TextBox3.Text & "_OAuthtkST.dat")
        My.Settings.m_strTokenSecret = objReader1.ReadLine()
        My.Settings.Save()
        objReader1.Close()

        'Authenticate.
        tw.AuthenticateWith(consumer, consumersecret, My.Settings.m_strToken, My.Settings.m_strTokenSecret)

        'Set Profile Image.
        If My.Computer.FileSystem.FileExists(Application.StartupPath + "/Images/" + tw.AccountInformation.ScreenName + ".png") Then
            frmMain.PictureBox1.Image = Image.FromFile(Application.StartupPath + "/Images/" + tw.AccountInformation.ScreenName + ".png")
        Else
            My.Computer.Network.DownloadFile(tw.AccountInformation.ProfileImageUrl, Application.StartupPath + "/Images/" + tw.AccountInformation.ScreenName + ".png")
            frmMain.PictureBox1.Image = Image.FromFile(Application.StartupPath + "/Images/" + tw.AccountInformation.ScreenName + ".png")
        End If

        'Fill account info.
        frmMain.Label1.Text = "@" + tw.AccountInformation.ScreenName
        frmMain.Label2.Text = tw.AccountInformation.FollowersCount & " Followers"
        frmMain.Label3.Text = tw.AccountInformation.FriendsCount & " Following"
        frmMain.Label4.Text = tw.AccountInformation.StatusesCount & " Tweets"
        frmMain.Text = "TWILT - @" & tw.AccountInformation.ScreenName

        'Fill timeline.
        frmMain.ListView1.Items.Clear()
        Dim tp As New TwitterParameters
        tp.Add(TwitterParameterNames.Count, 100)
        For Each entry As TwitterStatus In tw.HomeTimeline(tp)

            frmMain.ListView1.BeginUpdate()

            Dim n As New ListViewItem
            n = frmMain.ListView1.Items.Add(entry.CreatedAtLocalTime.ToString)
            n.SubItems.Add(entry.User.Name.ToString)
            n.SubItems.Add(entry.Text.ToString)
            frmMain.ListView1.EndUpdate()
            frmMain.ListView1.Refresh()
        Next

    End Sub

    ' New media added.
    Public Sub NewMedia()
        ' Get title, artist, and album cover image from file.
        Dim Filename As String = frmMain.ListBox3.SelectedItem
        frmMain.AxWindowsMediaPlayer1.URL = Filename
        frmMain.AxWindowsMediaPlayer1.Ctlcontrols.play()
        Dim song As String = frmMain.AxWindowsMediaPlayer1.currentMedia.getItemInfo("Title")
        Dim artist As String = frmMain.AxWindowsMediaPlayer1.currentMedia.getItemInfo("Artist")
        Try
            Dim id3 As New UltraID3
            id3.Read(frmMain.ListBox3.SelectedItem)
            Dim tag = id3.ID3v2Tag
            Dim pics = tag.Frames.GetFrames(MultipleInstanceID3v2FrameTypes.ID3v23Picture)
            Try
                frmMain.PictureBox3.Image = CType(pics(0), ID3v2PictureFrame).Picture
            Catch ex As Exception
                frmMain.PictureBox3.Image = Nothing
            End Try
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

        'Check authentication.
        Dim objReader As New System.IO.StreamReader(Application.StartupPath & "\Settings\" & frmLogin.TextBox3.Text & "_OAuthtk.dat")
        My.Settings.m_strToken = objReader.ReadLine()
        My.Settings.Save()
        objReader.Close()

        Dim objReader1 As New System.IO.StreamReader(Application.StartupPath & "\Settings\" & frmLogin.TextBox3.Text & "_OAuthtkST.dat")
        My.Settings.m_strTokenSecret = objReader1.ReadLine()
        My.Settings.Save()
        objReader1.Close()

        ' Authenticate.
        tw.AuthenticateWith(consumer, consumersecret, My.Settings.m_strToken, My.Settings.m_strTokenSecret)

        ' Send a tweet that my music changed.
        Try
            ' frmMain.ListBox2.Items.Add(song & " " & artist)
            tw.Update("I'm currently listening to " & song & " by " & artist & " using #TwiltMedia")

            ' Show the balloon in system tray.
            Dim tweetballoon As String
            tweetballoon = "I'm currently listening to " & song & " by " & artist & " using #TwiltMedia"

            frmMain.NotifyIcon1.ShowBalloonTip(1000, "New Tweet! - http://twilt.co.cc/", tweetballoon, ToolTipIcon.Info)
        Catch ex As Exception
            ' Oops, you either lost your connection or the tweet was a duplicate.
            Dim tweetballoon1 As String
            tweetballoon1 = "Error: " & ex.Message

            frmMain.NotifyIcon1.ShowBalloonTip(1000, "Warning!", tweetballoon1, ToolTipIcon.Warning)
        End Try

    End Sub

    ' Manual Tweet using out client.
    Public Sub ManualTweet()
        'Check authentication
        Dim objReader As New System.IO.StreamReader(Application.StartupPath & "\Settings\" & frmLogin.TextBox3.Text & "_OAuthtk.dat")
        My.Settings.m_strToken = objReader.ReadLine()
        My.Settings.Save()
        objReader.Close()

        Dim objReader1 As New System.IO.StreamReader(Application.StartupPath & "\Settings\" & frmLogin.TextBox3.Text & "_OAuthtkST.dat")
        My.Settings.m_strTokenSecret = objReader1.ReadLine()
        My.Settings.Save()
        objReader1.Close()

        ' Authenticate
        tw.AuthenticateWith(consumer, consumersecret, My.Settings.m_strToken, My.Settings.m_strTokenSecret)

        ' Send tweet.
        tw.Update(frmMain.TextBox1.Text + " #TwiltMedia")

        ' Show the balloon in system tray.
        Dim tweetballoon As String
        tweetballoon = frmMain.TextBox1.Text + " #TwiltMedia"

        frmMain.NotifyIcon1.ShowBalloonTip(1000, "New Tweet! - http://twilt.co.cc/", tweetballoon, ToolTipIcon.Info)

        ' Clear textbox
        frmMain.TextBox1.Text = Nothing

    End Sub

    ' Refresh.
    Public Sub NewRefresh()
        'Check authentication.
        Dim objReader As New System.IO.StreamReader(Application.StartupPath & "\Settings\" & frmLogin.TextBox3.Text & "_OAuthtk.dat")
        My.Settings.m_strToken = objReader.ReadLine()
        My.Settings.Save()
        objReader.Close()

        Dim objReader1 As New System.IO.StreamReader(Application.StartupPath & "\Settings\" & frmLogin.TextBox3.Text & "_OAuthtkST.dat")
        My.Settings.m_strTokenSecret = objReader1.ReadLine()
        My.Settings.Save()
        objReader1.Close()

        'Authenticate.
        tw.AuthenticateWith(consumer, consumersecret, My.Settings.m_strToken, My.Settings.m_strTokenSecret)

        'Fill account info.
        Try
            frmMain.Label1.Text = "@" + tw.AccountInformation.ScreenName
            frmMain.Label2.Text = tw.AccountInformation.FollowersCount & " Followers"
            frmMain.Label3.Text = tw.AccountInformation.FriendsCount & " Following"
            frmMain.Label4.Text = tw.AccountInformation.StatusesCount & " Tweets"

        Catch ex As Exception
            ' Show the error balloon in system tray.
            Dim tweetballoon As String
            tweetballoon = ex.Message

            frmMain.NotifyIcon1.ShowBalloonTip(1000, "Error", tweetballoon, ToolTipIcon.Error)
        End Try

        'Fill timeline.
        Try
            frmMain.ListView1.Items.Clear()
            Dim tp As New TwitterParameters
            tp.Add(TwitterParameterNames.Count, 100)
            For Each entry As TwitterStatus In tw.HomeTimeline(tp)
                frmMain.ListView1.BeginUpdate()
                Dim n As New ListViewItem
                n = frmMain.ListView1.Items.Add(entry.CreatedAtLocalTime.ToString)
                n.SubItems.Add(entry.User.Name.ToString)
                n.SubItems.Add(entry.Text.ToString)
                frmMain.ListView1.EndUpdate()
                frmMain.ListView1.Refresh()

            Next
        Catch ex As Exception
            ' Show the balloon in system tray.
            Dim tweetballoon As String
            tweetballoon = ex.Message

            frmMain.NotifyIcon1.ShowBalloonTip(1000, "Error", tweetballoon, ToolTipIcon.Error)
        End Try
    End Sub

    ' Update labels for the timer.
    Public Sub LabelUpdate()
        If frmMain.AxWindowsMediaPlayer1.playState = WMPLib.WMPPlayState.wmppsPlaying Then
            Dim song As String = frmMain.AxWindowsMediaPlayer1.currentMedia.getItemInfo("Title")
            Dim artist As String = frmMain.AxWindowsMediaPlayer1.currentMedia.getItemInfo("Artist")
            Dim album As String = frmMain.AxWindowsMediaPlayer1.currentMedia.getItemInfo("Album")

            frmMain.Label5.Text = song
            frmMain.Label6.Text = artist
            frmMain.Label7.Text = album
        Else
            ' Do nothing since no music is playing, else we have no pause feature D:
        End If
    End Sub

    ' Shuffle calculations. (not used yet)
    Public Sub ShuffleSongs()

        ' Variables
        Dim x, mix, temp As Integer
        Dim num As Integer = frmMain.ListBox3.Items.Count
        Dim randarray(num) As Integer
        Dim randnum As Random = New Random()

        For x = 0 To num
            randarray(x) = x
        Next x
        For x = 0 To num
            mix = randnum.Next(1, num + 1)
            temp = randarray(mix)
            randarray(mix) = randarray(x)
            randarray(x) = temp
        Next x

        For x = 1 To num
            ' I hate math ._.
        Next x

    End Sub

    ' Save Playlist.
    Public Sub SavePlaylist()
        Try
            oWrite = IO.File.CreateText(Application.StartupPath & "\playlist\playlist.txt")
            For Each items As String In frmMain.ListBox3.Items
                oWrite.WriteLine(items)
            Next
            oWrite.Close()
        Catch ex As Exception
            ' Show the balloon in system tray.
            Dim tweetballoon As String
            tweetballoon = "Error: " & ex.Message

            frmMain.NotifyIcon1.ShowBalloonTip(1000, "Warning!", tweetballoon, ToolTipIcon.Warning)
        End Try

    End Sub

    ' Load Playlist.
    Public Sub LoadPlaylist()
        Try
            Dim a As String = My.Computer.FileSystem.ReadAllText(Application.StartupPath & "\playlist\playlist.txt")
            Dim b As String() = a.Split(vbNewLine)
            frmMain.ListBox3.Items.AddRange(b)
        Catch ex As Exception
            ' Do nothing the file obviously doesnt exist... yet
        End Try
    End Sub

    ' Delete song from playlist.
    Public Sub DeleteSong()
        If MessageBox.Show("Remove this song from your playlist?", "Delete Song.", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) = Windows.Forms.DialogResult.Yes Then
            ' Yes, delete song.
            frmMain.ListBox3.Items.Remove(frmMain.ListBox3.SelectedItem)

            ' Skip next song because the song you are removing is currently playing and path cannot be null.
            If frmMain.ListBox3.SelectedIndex < frmMain.ListBox3.Items.Count - 1 Then
                frmMain.ListBox3.SelectedIndex = frmMain.ListBox3.SelectedIndex + 1
            End If

            ' Now save the playlist.
            Try
                oWrite = IO.File.CreateText(Application.StartupPath & "\playlist\playlist.txt")
                For Each items As String In frmMain.ListBox3.Items
                    oWrite.WriteLine(items)
                Next
                oWrite.Close()
            Catch ex As Exception
                ' Show the balloon in system tray.
                Dim tweetballoon As String
                tweetballoon = "Error: " & ex.Message

                frmMain.NotifyIcon1.ShowBalloonTip(1000, "Warning!", tweetballoon, ToolTipIcon.Warning)
            End Try
        Else
            ' No, then we do nothing.
        End If
    End Sub

    ' New ListView for song history.
    Public Sub SongHistoryLV()
        'Time stamp.
        Dim h As String = My.Computer.Clock.LocalTime.Hour
        Dim m As String = My.Computer.Clock.LocalTime.Minute

        ' Song information.
        Dim song As String = frmMain.AxWindowsMediaPlayer1.currentMedia.getItemInfo("Title")
        Dim artist As String = frmMain.AxWindowsMediaPlayer1.currentMedia.getItemInfo("Artist")
        Dim album As String = frmMain.AxWindowsMediaPlayer1.currentMedia.getItemInfo("Album")

        frmMain.ListView2.BeginUpdate()

        Dim n As New ListViewItem
        n = frmMain.ListView2.Items.Add(h & ":" & m)
        n.SubItems.Add(artist)
        n.SubItems.Add(song)
        n.SubItems.Add(album)
        frmMain.ListView2.EndUpdate()
        frmMain.ListView2.Refresh()
    End Sub

End Module
